package com.jevons.muffin.net.observer;

import android.text.TextUtils;


import com.jevons.muffin.net.HttpRequestManager;
import com.jevons.muffin.net.bean.NullObject;
import com.jevons.muffin.net.exception.ResponseException;
import com.jevons.muffin.net.inter.BaseObserver;
import com.jevons.muffin.utilcode.LogUtils;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLHandshakeException;

import io.reactivex.annotations.NonNull;
import io.reactivex.annotations.Nullable;
import io.reactivex.observers.DisposableObserver;
import retrofit2.HttpException;

/**
 * 网络请求任务
 * @author linaisheng
 * Created at 2019/3/19.
 */

public class BaseDisposable<T> extends DisposableObserver<T> implements BaseObserver<T> {

    private static final String TAG = BaseDisposable.class.getSimpleName();

    protected String taskId;

    public BaseDisposable(String taskId) {
        this.taskId = taskId;
    }

    public final String getTaskId() {
        return taskId;
    }

    @Override
    protected final void onStart() {
        //判断是否在请求中，防止重复请求
        if (TextUtils.isEmpty(taskId)) {
            //对于null和""来说，不记录在内
            return;
        }
        HttpRequestManager httpRequestManager = HttpRequestManager.getInstance();
        if (httpRequestManager.isRequesting(taskId)) {
            LogUtils.printWarn(TAG, "Task(" + taskId + "):正在请求中...");
            if (!this.isDisposed()) {
                this.dispose();
            }
        } else {
            HttpRequestManager.getInstance().putRequest(taskId, this);
        }
    }

    @Override
    public final void onNext(@NonNull T t) {
        onResponse(t);
    }

    void onResponse(@Nullable T t) {
        if (t.getClass().getName().equals(NullObject.class.getName())) {
            responseSuccess(null);
        } else {
            responseSuccess(t);
        }
    }


    @Override
    public void onError(@NonNull Throwable throwable) {
        responseError(dealThrowable(throwable));
        responseComplete();
    }

    static ResponseException dealThrowable(Throwable throwable) {
        if (throwable instanceof SocketTimeoutException) {
            // 请求超时
            return new ResponseException("请求超时", throwable, true);
        } else if (throwable instanceof ConnectException) {
            //网络连接超时
            String message = throwable.getCause().getMessage();
            if (message.contains("Network is unreachable")) {
                return new ResponseException(1002, "网络不可用", throwable, true);
            }
            return new ResponseException("网络连接超时", throwable, true);
        } else if (throwable instanceof SSLHandshakeException) {
            //安全证书异常
            return new ResponseException("安全证书异常", throwable, true);
        } else if (throwable instanceof HttpException) {
            int code = ((HttpException) throwable).code();
            if (code == 504) {
                return new ResponseException(504,
                        "网络异常，请检查您的网络状态", throwable, true);
            } else if (code == 404) {
                return new ResponseException(404,
                        "请求的地址不存在", throwable, true);
            } else {
                return new ResponseException(code, "请求失败",
                        throwable, true);
            }
        } else if (throwable instanceof UnknownHostException) {
            return new ResponseException("域名解析失败", throwable, true);
        } else if (throwable instanceof ResponseException) {
            //业务定义错误
            return (ResponseException) throwable;
        } else {
            //未分类错误
            return new ResponseException("请求失败", throwable);
        }
    }

    //请求完成
    final void responseComplete(){
        HttpRequestManager.getInstance().removeRequest(taskId);
    }


    //请求成功
    private void responseSuccess(T t) {
        responseSuccess(taskId, t);
        responseComplete();
    }

    //请求错误
    private void responseError(ResponseException exception) {
       responseError(taskId, exception);
    }


    @Override
    public final void onComplete() {
        responseComplete();
    }


    @Override
    public void responseSuccess(String taskId, T response) {

    }

    @Override
    public void responseError(String taskId, ResponseException exception) {

    }
}
